import {Dimension, selectMyPm, selectMyPmById, selectPmData} from '@/api/myPerformance'
import deepClone from '@/libs/deepClone'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {ref, computed} from 'vue'
const {message} = ant_design_vue

function useMyPm() {
  //? 绩效详情 -----------------------------------
  let pm = ref<MyPm.Pm>()
  function getPmByPmId(data: {
    pmId: number
    updatePm?: boolean
    success?: (data: MyPm.Pm) => void
  }) {
    selectMyPmById({pmId: data.pmId})
      .then(res => {
        data.success && data.success(res.data)
        data.updatePm && setPm(res.data)
      })
      .catch(err => {})
  }
  /**根据PmId绩效Id 更新绩效 */
  function updatePmByPmId(data: {pmId: number}) {
    selectMyPmById({pmId: data.pmId})
      .then(res => {
        setPm(res.data)
      })
      .catch(err => {})
  }
  function setPm(data: MyPm.Pm) {
    pm.value = data
  }

  //? 绩效列表 -----------------------------------
  let myPmList = ref<MyPm.Pm[]>([])
  function setMyPmList(data: MyPm.Pm[]) {
    myPmList.value = data
  }
  /**获取指定用户的绩效列表 */
  function getMyPmListByUserDDId({
    userDDId,
    updateMyPmList = false,
    success
  }: {
    userDDId: string
    updateMyPmList?: boolean
    success?: (data: MyPm.Pm[]) => void
  }) {
    selectMyPm({userDDId: userDDId})
      .then(res => {
        updateMyPmList && setMyPmList(res.data)
        success && success(res.data)
      })
      .catch(err => {})
  }

  //? 绩效数据 -----------------------------------
  /**
   * 绩效数据
   * 包含绩效中的维度以及指标
   */
  let pmDataList = ref<MyPm.PmData[] | undefined>(undefined)
  function setPmDataList(data: MyPm.PmData[]) {
    pmDataList.value = data
  }

  /**根据绩效id获取绩效中的维度及其下的指标 */
  function getPmDataByPmId({
    pmId,
    updatePmData = false,
    success,
    error
  }: {
    pmId: number
    updatePmData?: boolean
    success?: (data: MyPm.PmData[]) => void
    error?: () => void
  }) {
    selectPmData({pmId})
      .then(res => {
        // let nData = []
        // nData.push(res.data[2])
        // nData.push(res.data[3])
        updatePmData && setPmDataList(res.data || [])
        success && success(res.data || [])
      })
      .catch(err => {
        error && error()
      })
  }

  /**所有维度权重 */
  const dimensionWeightCountByPmDataList = computed(
    () => eval((pmDataList.value || []).map(dimen => dimen.pmDimensionWeight).join('+')) as number
  )

  /**指标总数 */
  const targetCountByPmDataList = computed(() => {
    let count = 0
    if (!pmDataList.value) return count
    if (!pmDataList.value.length) return count
    for (let i = 0; i < pmDataList.value.length; i++) {
      const pmData = pmDataList.value[i]
      count += pmData.pmTargetList.length
    }
    return count
  })

  /**所有指标权重 */
  const targetWeightCountByPmDataList = computed(
    () =>
      eval(
        (pmDataList.value || [])
          .map(item =>
            item.pmTargetList
              .filter(item => item.isBonus !== 1)
              .map(target => target.pmTargetWeight)
          )
          .flat(Infinity)
          .join('+')
      ) as number
  )

  /**
   * 自评的总分
   *
   * 数组层级表示说明
   * 第一层数组代表维度数量
   * 第二层数组代表自评人数量
   */
  const totalScoreBySelf = computed(() =>
    // 循环绩效数据，维度
    ((deepClone(pmDataList.value) as typeof pmDataList.value) || []).map(dimen => {
      // 获取维度中所有指标中的自评数据
      let selfScoreList = dimen.pmTargetList
        .map(target =>
          (target.scoreSelfCheckList || []).map(scoreself => {
            scoreself.score = scoreself.score * (target.pmTargetWeight / 100)
            return scoreself
          })
        )
        .flat(1)

      console.log(selfScoreList)

      let returnData: MyPm.ScoreSelfCheck[] = []

      for (let i = 0; i < selfScoreList.length; i++) {
        const selfScore = selfScoreList[i]
        if (!selfScore) continue
        let index = returnData.findIndex(item => item.makeUserDDId === selfScore.makeUserDDId)
        if (index !== -1) {
          returnData[index].score += selfScore.score
        } else {
          returnData.push(selfScore)
        }
      }

      return returnData
    })
  )

  //? 评分阶段 -----------------------------------
  // const isScore

  //? 校验维度中指标权重总和是否超出 -----------------------------------
  function checkTargetWeight(dimensions: Dimension[]) {
    for (let i = 0; i < dimensions.length; i++) {
      const dimension = dimensions[i]

      // 校验
      if (dimension.pmTargetList.length <= 0) {
        message.warning(`维度:${dimension.pmDimensionName} 未制定指标`)
        return false
      }

      let targetWeight: number = 0

      for (let j = 0; j < dimension.pmTargetList.length; j++) {
        const target = dimension.pmTargetList[j]

        // 如果当前指标的操作类型为删除，则跳转权重检验
        if (target.makeProperty === 'delete') continue

        // 如果当前指标为加分项，则跳过权重检验
        if (target.isBonus == 1) {
          continue
        }

        // 如果当前指标没有权重 或  权重为零时，返回false
        if (!target.pmTargetWeight) {
          message.warning(
            `维度:${dimension.pmDimensionName} 中的指标:${target.pmTargetName} 未设置权重`
          )
          return false
        }

        // 如果当前指标有权重,加和当前维度内指标的权重总和
        targetWeight += Number(target.pmTargetWeight)
      }

      console.log('提交权重', targetWeight)
      if (dimension.pmDimensionWeight > targetWeight) {
        message.warning(
          `维度:${dimension.pmDimensionName}，所有指标的权重小于${dimension.pmDimensionWeight}`
        )
        return false
      } else if (dimension.pmDimensionWeight < targetWeight) {
        message.warning(
          `维度：${dimension.pmDimensionName}，所有指标的权重大于${dimension.pmDimensionWeight}`
        )
        return false
      }
    }
    return true
  }

  return {
    getPmByPmId,
    pm,
    updatePmByPmId,
    setPm,
    myPmList,
    setMyPmList,
    getMyPmListByUserDDId,
    pmDataList,
    setPmDataList,
    getPmDataByPmId,
    targetCountByPmDataList,
    targetWeightCountByPmDataList,
    dimensionWeightCountByPmDataList,
    checkTargetWeight,
    totalScoreBySelf
  }
}

export default useMyPm
